import { UserinfoDialogComponent } from './../userinfo-dialog/userinfo-dialog.component';
import { MatDialog } from '@angular/material';
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { RestService } from '../../services/rest.service';
import { GridOptions } from 'ag-grid/main';

import * as _ from 'lodash';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class UsersComponent {
  gridOptions: GridOptions;
  columnDefs: any[];
  rowData: any[];

  constructor(public dialog: MatDialog,
              public restService: RestService) {
    this.gridOptions = this.restService.getGeneralGridOptions();
    this.columnDefs = [
      {headerName: '账号', field: 'name'},
      {headerName: '姓名', field: 'desc'},
      {headerName: '联系方式', field: 'tel'},
      {headerName: '邮箱', field: 'email'},
      {headerName: '角色', field: 'role'}
    ];
    this.restService.addCheckboxColumn(this.columnDefs);
    this.rowData = null;
  }

  onSelectionChanged() {
    console.log('row selection changed');
  }

  refresh() {
    this.restService.get('/users').subscribe(data => {
      this.rowData = _.isArray(data) ? data : [];
    }, error => {
        this.rowData = [];
    });
  }

  onGridReady(params) {
    params.api.sizeColumnsToFit();
    this.refresh();
  }

  selectAllRows() {
    this.gridOptions.api.selectAll();
  }

  getUser() {
    this.restService.get('/user/admin').subscribe(data => {
      console.log('got it');
    }, error => {
      console.error('failed to get user admin');
    });
  }

  addUser() {
    this.dialog.open(UserinfoDialogComponent, {
      width: '400px',
      disableClose: true,
      data: {}
    }).afterClosed().subscribe(data => {
      if (!data) {
        return;
      }

      this.refresh();
    });
  }

  deleteUser() {
    const rows = this.gridOptions.api.getSelectedRows();
    if (_.isEmpty(rows)) {
      return;
    }

    rows.forEach(row => {
      this.deleteOneUser(row);
    });
  }

  deleteOneUser(row) {
    this.restService.delete('user/' + row.name).subscribe(data => {
      this.refresh();
    }, error => {
      console.error('Failed to delete user ' + row.name);
    });
  }
}
